(function (G) {
    G.vue({
        data: {
            title: '',
            btns: {
                actions: []
            },
            actions: {},
            task: {},
            flow: {},
            details: [],
            userInfo: {},
            form: {
                userId: '',
                remark: '',
                toNodeId: '',
                toUsers: []
            },
            node:{},
            actionModels:{},
            toUserInfos:[],
            submiting:false
        },
        methods: {
            changeToNodeId(value) {
                if(value.detail && value.detail.value) value = value.detail.value
                this.data.form.toNodeId = value
                let models = G.clone(this.data.actionModels[value]),values = {}
                this.setData({
                    form:this.data.form
                })
                if (this.data.actions[value]) {
                    let defaultValue = []
                    for(let i = 0; i < this.data.actions[value].length; i ++){
                        defaultValue.push(this.data.actions[value][i].value)
                    }
                    defaultValue = defaultValue.join(',')
                    G.merge(models,{
                        toUsers: {
                            label: '指定处理人',
                            rule: {
                                NotNull: true
                            },
                            defaultValue,
                            // defaultValue: this.data.actions[value][0].value,
                            attr: {
                                actions: this.data.actions[value]
                            },
                            type: 'checkbox',
                            web: true
                        },
                        remark: {
                            label: '处理意见',
                            type: 'textarea',
                            rule:{ NotNull:true },
                            attr:{
                                placeholder:'请填写处理意见'
                            },
                            web: true
                        }
                    })
                } else {
                    values.toUsers = this.data.actions[value] ? this.data.actions[value][0] : undefined
                    G.merge(models,{
                        remark: {
                            rule:{ NotNull:true },
                            label: '处理意见',
                            attr:{
                                placeholder:'请填写处理意见'
                            },
                            type: 'textarea',
                            web: true
                        }
                    })
                }
                this.selectComponent('#actionForm').init(models, values, false, [])
            },
            action1(){
                let actionFormData = this.selectComponent('#actionForm').submit()
                if (!actionFormData) return false
                if (actionFormData.toUsers instanceof Array) actionFormData.toUsers = actionFormData.toUsers.join(',')
                let form = this.data.actionModels[this.data.form.toNodeId]
                G.put('/v1/task/update',{
                    taskId:this.data.task.id,
                    toUsers:actionFormData.toUsers,
                    toNodeId:this.data.form.toNodeId,
                    form,
                    data:actionFormData,
                    notify_url:this.data.task.notify_url.replace(/^\{(.+)\}/,($0,$1) => {
                        return G.Storage.get($1)
                    })
                }).then(res => {
                    if (res.errorMsg) {
                        G.toask(res.errorMsg)
                    }else{
                        G.alert('操作成功').then(()=>{
                            this.$back()
                        })
                    }
                })
            },
            //节点操作
            action() {
                // let node = this.data.details[this.data.details.length - 1]
                // let nodeForm = this.selectComponent('#' + node.id)
                // let data;
                // if (nodeForm) {
                //     data = nodeForm.submit()
                //     if (!data) return false
                // }
                let node = this.data.node
                let actionFormData = this.selectComponent('#actionForm').submit()
                if (!actionFormData) return false
                if (actionFormData.toUsers instanceof Array) actionFormData.toUsers = actionFormData.toUsers.join(',')
                let actionName = ''
                for(let i = 0; i < this.data.btns.actions.length; i ++) {
                    if(this.data.btns.actions[i].value == this.data.form.toNodeId){
                        actionName = this.data.btns.actions[i].name
                        break
                    }
                }
                let form = this.data.actionModels[this.data.form.toNodeId]
                // for (let key in node.form)
                //     if (!node.form[key].web) form[key] = node.form[key]
                // 创建最新操作记录
                this.setData({
                    submiting:true
                })
                G.post('/api/model/f_taskDetail', {
                    form: JSON.stringify(form),
                    // data: data ? JSON.stringify(data) : '',
                    data:actionFormData ? JSON.stringify(actionFormData) : '',
                    name:`${node.name}[${actionName}]`,
                    status: 2,
                    userId: this.data.userInfo.id,
                    toNodeId: this.data.form.toNodeId,
                    f_nodeId: node.id,
                    f_taskId: this.data.task.id,
                    f_flowId: node.f_flowId,
                    ...actionFormData
                }).then(taskDetail => {
                    if (!taskDetail.errorMsg) {
                        try {
                            taskDetail.data = JSON.parse(taskDetail.data)
                        } catch (e) {
                            console.log(e)
                            taskDetail.data = null
                        }
                        //获取下一节点
                        G.get('/api/model/f_node', {
                            id: this.data.form.toNodeId
                        }).then(node => {
                            if (node.id) {
                                //获取操作
                                G.get('/api/model/f_line', {
                                    fromNodeId: node.id
                                }).then(lines => {
                                    node.status = lines.length ? 1 : 2
                                    G.put('/api/model/f_task', {
                                        id: this.data.task.id,
                                        status: node.status,
                                        toUsers: actionFormData.toUsers,
                                        f_nodeId: this.data.form.toNodeId || ''
                                    }).then(res => {
                                        if (!res.errorMsg) {
                                            let rc = {
                                                task: this.data.task, //流程任务信息
                                                currentNode: node, //当前节点信息
                                                prevDetail: taskDetail //前一处理结果
                                            }
                                            //通知业务系统
                                            if (this.data.task.notify_url) {
                                                G.post(this.data.task.notify_url, rc).then(res => {
                                                    if (res.task) G.put('/api/model/f_task', {
                                                        id: this.data.task.id,
                                                        ...res.task
                                                    }).then(res => {})
                                                    //this.triggerEvent('back', res)
                                                    if (!res.errorMsg) {
                                                        G.toask('操作成功').then(() => {
                                                            this.$back()
                                                        })
                                                    }

                                                })
                                            } else {
                                                //this.triggerEvent('back', rc)
                                                if (!rc.errorMsg) {
                                                    G.toask('操作成功').then(() => {
                                                        this.$back()
                                                    })
                                                }
                                            }
                                        } else {
                                            //this.triggerEvent('back', res)
                                            if (!res.errorMsg) {
                                                G.toask('操作成功').then(() => {
                                                    this.$back()
                                                })
                                            }
                                        }
                                    })
                                })
                            } else {
                                //this.triggerEvent('back', node)
                                if (!node.errorMsg) {
                                    G.toask('操作成功').then(() => {
                                        this.$back()
                                    })
                                }
                            }
                        })
                    } else {
                        G.toask('操作失败,' + taskDetail.errorMsg).then(() => {
                            this.$back()
                        })
                    }
                })
            },
            init(taskId) {
                new Promise(next => { //获取任务详情
                    G.get('/api/model/f_task', {
                        id: taskId,
                        sql: {
                            join: {
                                f_flowId: {
                                    type: 'LEFT',
                                    name: 'f_flow',
                                    key: 'id',
                                    projection: {
                                        notify_url: 1,
                                        name: 'f_flowName'
                                    }
                                }
                            }
                        }
                    }).then(task => {
                        this.setData({
                            task
                        })
                        wx.setNavigationBarTitle({
                            title: task.title || task.f_flowName,
                        })
                        next()
                    })
                }).then(() => { //获取已完成节点并处理
                    return new Promise(next => {
                        G.get('/api/model/f_taskDetail', {
                            f_taskId: this.data.task.id,
                            join: 'user',
                            sql: {
                                sort: {
                                    createTime: 1
                                }
                            }
                        }).then(details => {
                            if (!details.length) details = []
                            for (let i = 0; i < details.length; i++) {
                                details[i].readOnly = true
                                if(details[i].form.tit) details[i].form.tit = null
                                details[i].form = G.merge({
                                    tit: {
                                        label: '',
                                        type: 'title',
                                        web: true
                                    }
                                },details[i].form ? JSON.parse(details[i].form) : {})
                                details[i].form.tit.label = `${details[i].name} 由 ${details[i].userName} 于${details[i].createTimeString}完成`
                                if (details[i].data) {
                                    details[i].data = JSON.parse(details[i].data)
                                    if (details[i].remark) {
                                        details[i].form.remark = {
                                            rule:{ NotNull:true },
                                            label: '处理意见',
                                            attr:{
                                                placeholder:'请填写处理意见'
                                            },
                                            type: 'textarea'
                                        }
                                        details[i].data.remark = details[i].remark
                                    }
                                }
                            }
                            this.setData({
                                details
                            })
                            //前一步操作指派自己为操作人之一可进行下一步操作
                            if (details.length &&
                                details[details.length - 1].toUsers &&
                                details[details.length - 1].toUsers.indexOf(this.data.userInfo.userId) > -1) {
                                next()
                            } else {
                                G.get('/api/model/f_node', {
                                    id: this.data.task.f_nodeId
                                }).then(node => {
                                    if(this.data.task.status == 1 && this.data.task.toUsers){
                                        G.get('/api/model/user',{
                                            id:{
                                                $in:this.data.task.toUsers.split(',')
                                            },
                                            sql:'user_unit'
                                        }).then(res => {
                                            this.setData({
                                                btns: {
                                                    actions: []
                                                },
                                                actions: {},
                                                node,
                                                toUserInfos:res
                                            })
                                        })
                                    }else{
                                        this.setData({
                                            btns: {
                                                actions: []
                                            },
                                            actions: {},
                                            node
                                        })
                                    }
                                })
                                
                            }
                        })
                    })
                }).then(() => { //获取当前处理表单
                    return new Promise(next => {
                        if (this.data.task.f_nodeId) {
                            G.get('/api/model/f_node', {
                                id: this.data.task.f_nodeId
                            }).then(node => {
                                if (!node.errorMsg) {
                                    // node.form = G.merge({
                                    //     tit: {
                                    //         label: node.name,
                                    //         type: 'title',
                                    //         web: true
                                    //     }
                                    // }, node.form ? JSON.parse(node.form) : {})
                                    node.form = node.form ? JSON.parse(node.form) : {}
                                    // if (node.data) node.data = JSON.parse(node.data)
                                    // this.data.actionModels.push(node)
                                    // this.setData({
                                    //     actionModels: node.form
                                    // })
                                    next(node)
                                }else{
                                    next()
                                }
                            })
                        }
                        else{
                            next()
                        }
                    })
                }).then((node) => { //获取当前处理操作
                    let _actionModels = node.form || {}
                    return new Promise(next => {
                        G.get('/api/model/f_line', {
                            fromNodeId: this.data.task.f_nodeId
                        }).then(lines => {
                            if (lines.length) {
                                let btns = {
                                        actions: []
                                    },
                                    actions = {}, promises = [],actionModels = {}
                                for (let i = 0; i < lines.length; i++) {
                                    let line = lines[i]
                                    actionModels[lines[i].toNodeId] = _actionModels[lines[i].toNodeId] || G.clone(_actionModels)
                                    promises.push(new Promise(next => {
                                        if (i == 0) this.data.form.toNodeId = lines[i].toNodeId
                                        let users = []
                                        if(lines[i].type == 1) {
                                            for(let j = 0; j < this.data.details.length; j ++){
                                                let detail = this.data.details[j]
                                                if(line.fromNodeId == detail.toNodeId && line.toNodeId == detail.f_nodeId){
                                                    users = [{ value:detail.userId,name:detail.userName || '申请人' }]
                                                }
                                            }
                                            lines[i].userType = 'bohui'
                                            if(!users.length) lines[i].userType = 'prev'
                                        }
                                        switch(lines[i].userType){
                                            case 'start':
                                                users = [{ value:this.data.task.userId,name:'发起人' }]
                                                break;
                                            case 'prev':
                                                users = [{ value:this.data.details[this.data.details.length - 1].userId,name:'上一处理人' }]
                                                break;
                                            case 'self':
                                                users = [{ value:this.data.userInfo.userId,name:'当前处理人' }]
                                                break;
                                            case 'select':
                                                users = G.string(lines[i].users).parse([])
                                                break;
                                        }
                                        if(lines[i].checkUnit){
                                            let userIds = []
                                            for(let j = 0; j < users.length; j ++) userIds.push(users[j].value)
                                            G.get('/api/model/user', {
                                                id:{ $in:userIds }
                                            }).then(_users => {
                                                users = []
                                                for(let i = 0; i < _users.length; i ++) {
                                                    // if(new RegExp('^' + _users[i].unitId).test(this.data.task.unitId)) {
                                                    if(_users[i].unitId == this.data.task.unitId) {
                                                        users.push({
                                                            value:_users[i].id,
                                                            name:_users[i].name
                                                        })
                                                    }
                                                }
                                                actions[lines[i].toNodeId] = []
                                                for (let j = 0; j < users.length; j++) {
                                                    if (users[j] && users[j].value) actions[lines[i].toNodeId].push(users[j])
                                                }
                                                btns.actions.push({
                                                    value: lines[i].toNodeId,
                                                    name: lines[i].name
                                                })
                                                next()
                                            })
                                        }else{
                                            actions[lines[i].toNodeId] = []
                                            for (let j = 0; j < users.length; j++) {
                                                if (users[j] && users[j].value) actions[lines[i].toNodeId].push(users[j])
                                            }
                                            btns.actions.push({
                                                value: lines[i].toNodeId,
                                                name: lines[i].name
                                            })
                                            next()
                                        }
                                    }))
                                }
                                Promise.all(promises).then(() => {
                                    this.setData({
                                        btns,
                                        actions,
                                        actionModels,
                                        node
                                    })
                                    this.changeToNodeId(this.data.form.toNodeId)
                                })
                            }
                            next()
                        })
                    })
                })
            }
        },
        mounted(query) {
            this.setData({
                userInfo: G.Storage.get('userInfo')
            })
            let taskId = query.taskId
            if (taskId) this.init(taskId)
        }
    })
})(wx.$)